<?php
/**
 * 更新单个item
 * author: JiangJun
 * CreateTime:2021/7/25 22:46
 */

require '../vendor/autoload.php';

use Aws\DynamoDb\Exception\DynamoDbException;
use Aws\DynamoDb\Marshaler;

$sdk = new Aws\Sdk([
    'region'   => 'us-west-2',
    'version'  => 'latest'
]);

$dynamodb = $sdk->createDynamoDb();
$marshaler = new Marshaler();

$tableName = 'Movies';

$year = 2015;
$title = 'The Big New Movie';

//更新要用到的主键key，用于指定要更新哪条item
$key = $marshaler->marshalJson('
    {
        "year": ' . $year . ', 
        "title": "' . $title . '"
    }
');

//更新的数据
$eav = $marshaler->marshalJson('
    {
        ":r": 5.5 ,
        ":p": "Everything happens all at once.",
        ":a": [ "Larry", "Moe", "Curly" ]
    }
');

$params = [
    'TableName' => $tableName,
    'Key' => $key,//通过主键，查找到要更新的条件
    'UpdateExpression' =>//更新表达式，这里指定了要更新的字段和对应的值（用占位符表示）
        'set info.rating = :r, info.plot=:p, info.actors=:a',
    'ExpressionAttributeValues'=> $eav,//绑定的变量
    'ReturnValues' => 'UPDATED_NEW'//返回新的值
];

//我的测试
$key2=$marshaler->marshalItem([
    'year'=>2021,
    'title'=>'Jiang Jun',
]);

$newValues=$marshaler->marshalItem([
    ':inc'=>3,
    ':description'=>'不可描述小电影'
]);

$params2 = [
    'TableName' => $tableName,
    'Key' => $key2,//通过主键，找到条目后更新
    'UpdateExpression' =>//更新表达式，这里指定了要更新的字段和对应的值（用占位符表示）
        'set info.rating =info.rating + :inc, description = :description',//注意里面有“增加数量”的例子
    'ExpressionAttributeValues'=> $newValues,//绑定的变量
    'ReturnValues' => 'UPDATED_NEW'//配置为只返回更新的属性和值
];

try {
    $result = $dynamodb->updateItem($params2);
    echo "Updated item.\n";
    //将返回被更新的属性
    print_r($result['Attributes']);

} catch (DynamoDbException $e) {
    echo "Unable to update item:\n";
    echo $e->getMessage() . "\n";
}